<?Php
/*
 * 菜单
 */
class Menu
{
	/*
	 * 载入菜单配置, 输出经过处理的template变量
	 *
	 * @param	string	$menu_type  see site::type()
	 * @return array
	 */
	public static function load ($menu_type)
	{
		$menu   = array();
		$config = Kohana::config('menu.' . $menu_type);
		if (empty($config))
			return $menu;

		$request   = Request::initial();
		$initial_c = $request->controller();
		$initial_a = $request->action();
		$initial_r = '/'.$request->uri();

		foreach ($config as $group_name => $items)
		{
			$group  = array('name' => $group_name, 'items' => array(), 'link' => $items['link']);
			$controller = Arr::get($items, 'controller');
			foreach ($items['items'] as $label => $item)
			{
				$item['name']     = $label;
				$c = Arr::get($item, 'controller', $controller);
				$m = Arr::get($item, 'action', 'index');
				$r = Arr::get($item, 'link',   NULL);

				if ($c == $initial_c)
				{
					if (is_array($m))
					{
						foreach ($m as $mr)
							if ($mr == $initial_a)
							{
								$item['active']  = TRUE;
								$group['active'] = TRUE;
							}
					}
					else if ($m == $initial_a)
					{
						$item['active']  = TRUE;
						$group['active'] = TRUE;
					}
					else if ($r === $initial_r)
					{
						$item['active']  = TRUE;
						$group['active'] = TRUE;
					}
				}

				if (! isset($item['link']))
					$item['link'] = is_array($m) ? "/$c/{$m[0]}" : "/$c/$m";

				$group['items'][] = $item;
			}

			$menu[] = $group;
		}

		return $menu;
	}
}
